package com.xu.mybatis.dao;

import com.xu.mybatis.pojo.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

/**
 * Created by xu on 2017/3/8.
 */
public class UserdaoImpl implements Userdao {
    //需要向dao实现类中注入SqlSessionFactory
    //这里通过构造方法注入
    private SqlSessionFactory sqlSessionFactory;
    public UserdaoImpl(SqlSessionFactory sqlSessionFactory){
        this.sqlSessionFactory=sqlSessionFactory;
    }
    //按照id查询
    @Override
    public User findUserById(int id) throws Exception {
        SqlSession sqlSession=sqlSessionFactory.openSession();
        User user=sqlSession.selectOne("test.findUserById",id);
        sqlSession.close();
        return user;
    }
    //按照姓名查询
    @Override
    public List<User> findUserByName(String name) throws Exception {
        SqlSession sqlSession=sqlSessionFactory.openSession();
         List list=sqlSession.selectList("test.findUserByName",name);
        sqlSession.close();
        return list;
    }
    //新增用户
    @Override
    public void addUser(User user) throws Exception {
        SqlSession sqlSession=sqlSessionFactory.openSession();
        //提交事务
        sqlSession.commit();
        sqlSession.close();
    }
    //修改用户
    @Override
    public void updateUser(User user) throws Exception {
        SqlSession sqlSession=sqlSessionFactory.openSession();
        //提交事务
        sqlSession.commit();
        sqlSession.close();
    }
    //删除用户
    @Override
    public void deleteUser(int id) throws Exception {
        SqlSession sqlSession=sqlSessionFactory.openSession();
        //提交事务
        sqlSession.commit();
        sqlSession.close();
    }
}
